package com.yk.airline.component.ExcelExport.impl;/**
 * Created by wangzhili on 2018/2/2.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yk.airline.component.ExcelExport.api.IExcelExport;
import com.yk.airline.dao.analysisdata.api.IAnalysisDataDao;
import com.yk.airline.model.AnalysisDataModel;
import com.yk.airline.model.CaptureMarkModel;
import com.yk.airline.model.ExportExcelModel;
import com.yk.airline.util.AnalysisDataModelComparator;
import com.yk.exportExcel.entity.Template;
import com.yk.exportExcel.manage.TemplateManage;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.io.OutputStream;
import java.util.*;

/**
 * Project Name:airlinecrawler
 * File Name:ExcelExportImpl
 * Package Name:com.yk.airline.component.ExcelExportImpl.impl
 * Date:2018/2/2 16:14
 * Author:wangzhili
 * Description:
 * Copyright (c) 2018, 重庆云凯科技有限公司 All Rights Reserved.
 */
@Service("excelExport")
public class ExcelExportImpl implements IExcelExport {

    @Resource(name = "analysisDataDao")
    private IAnalysisDataDao analysisDataDao;

    /**
     * 导出excel
     *
     * @param captureMarkModel 批次实体
     * @param websites         网站集合
     * @param airCompanies     公司集合
     * @param calendar         时间T
     * @param template         excel模板选择（A B）
     * @param os               导出位置
     */
    public void exportExcel(CaptureMarkModel captureMarkModel, List<String> websites, List<String> airCompanies, Calendar calendar, Template template, OutputStream os) {

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);


        List<AnalysisDataModel> list;
        HashMap<String, List<AnalysisDataModel>> collection;
        List<Map<String, String>> result;
        ExportExcelModel exportExcelModel;
        List<ExportExcelModel> exportExcelModels = new ArrayList<>();
        for (String website : websites) { //针对不同网站（实质上是在同一个工作簿中，分多个表格）
            list = this.analysisDataDao.queryByCondition(captureMarkModel, website, airCompanies);
            collection = buildCollection(list);
            result = build(collection, calendar, template);
            exportExcelModel = new ExportExcelModel(result, website);
            exportExcelModels.add(exportExcelModel);
        }
        exportExcel(exportExcelModels, template, os);
    }

    /**
     * 把相同航班不同天数的集合，分开存储HashMap（标识，同一个航班不同天数的集合）
     *
     * @param list
     * @return
     */
    private HashMap<String, List<AnalysisDataModel>> buildCollection(List<AnalysisDataModel> list) {
        HashMap<String, List<AnalysisDataModel>> collection = new HashMap<>();
        for (AnalysisDataModel analysisDataModel : list) {
            String id = analysisDataModel.getAirLine() + analysisDataModel.getAirCompany() + analysisDataModel.getFlightNumber();
            if (!collection.containsKey(id)) {
                collection.put(id, new ArrayList<>());
            }
            collection.get(id).add(analysisDataModel);
        }
        return collection;
    }

    /**
     * 构建数据
     *
     * @param collection
     * @param calendar
     * @param template
     * @return
     */
    private List<Map<String, String>> build(HashMap<String, List<AnalysisDataModel>> collection, Calendar calendar, Template template) {
        List<Map<String, String>> result = new ArrayList<>();
        Calendar t = Calendar.getInstance();
        t.setTimeInMillis(calendar.getTimeInMillis());

        Calendar t2 = Calendar.getInstance();
        t2.setTimeInMillis(calendar.getTimeInMillis());
        t2.add(Calendar.DATE, 2);

        Calendar t6 = Calendar.getInstance();
        t6.setTimeInMillis(calendar.getTimeInMillis());
        t6.add(Calendar.DATE, 6);

        Calendar t16 = Calendar.getInstance();
        t16.setTimeInMillis(calendar.getTimeInMillis());
        t16.add(Calendar.DATE, 16);

        String airLine = null;
        String depart = null;
        String arrive = null;

        Map<String, Map<String, String>> allMap = new HashMap<>();
        for (Map.Entry<String, List<AnalysisDataModel>> entry : collection.entrySet()) {
            if (!allMap.containsKey(entry.getKey())) {
                allMap.put(entry.getKey(), new HashMap<>());
            }
            for (AnalysisDataModel model : entry.getValue()) {

                Map<String, String> map = allMap.get(entry.getKey());
                airLine = model.getAirLine();
                JSONObject object = JSON.parseObject(airLine);
                depart = object.get("depart").toString();
                arrive = object.get("arrive").toString();

                map.put("flightLine", depart + "-" + arrive);
                map.put("airCompany", model.getAirCompany());
                map.put("flightNumber", model.getFlightNumber());
                if ("TemplateTwo".equals(template.toString())) {
                    if (model.getDepartureTime().getTime() > t.getTimeInMillis() && model.getDepartureTime().getTime() < t2.getTimeInMillis()) {
                        map.put("specialPriceT", String.valueOf(model.getSpecialPrice()));
                        map.put("preferredPriceT", String.valueOf(model.getPreferredPrice()));
                        map.put("preferredInformationT", String.valueOf(model.getPreferredInfo()));
                    } else if (model.getDepartureTime().getTime() > t2.getTimeInMillis() && model.getDepartureTime().getTime() < t6.getTimeInMillis()) {
                        map.put("specialPriceT2", String.valueOf(model.getSpecialPrice()));
                        map.put("preferredPriceT2", String.valueOf(model.getPreferredPrice()));
                        map.put("preferredInformationT2", String.valueOf(model.getPreferredInfo()));
                    } else if (model.getDepartureTime().getTime() > t6.getTimeInMillis() && model.getDepartureTime().getTime() < t16.getTimeInMillis()) {
                        map.put("specialPriceT6", String.valueOf(model.getSpecialPrice()));
                        map.put("preferredPriceT6", String.valueOf(model.getPreferredPrice()));
                        map.put("preferredInformationT6", String.valueOf(model.getPreferredInfo()));
                    } else {
                        map.put("specialPriceT16", String.valueOf(model.getSpecialPrice()));
                        map.put("preferredPriceT16", String.valueOf(model.getPreferredPrice()));
                        map.put("preferredInformationT16", String.valueOf(model.getPreferredInfo()));
                    }
                } else {
                    if (model.getDepartureTime().getTime() > t.getTimeInMillis() && model.getDepartureTime().getTime() < t2.getTimeInMillis()) {
                        map.put("lowestPriceT", String.valueOf(model.getLowestPrice()));
                    } else if (model.getDepartureTime().getTime() > t2.getTimeInMillis() && model.getDepartureTime().getTime() < t6.getTimeInMillis()) {
                        map.put("lowestPriceT2", String.valueOf(model.getLowestPrice()));
                    } else if (model.getDepartureTime().getTime() > t6.getTimeInMillis() && model.getDepartureTime().getTime() < t16.getTimeInMillis()) {
                        map.put("lowestPriceT6", String.valueOf(model.getLowestPrice()));
                    } else {
                        map.put("lowestPriceT16", String.valueOf(model.getLowestPrice()));
                    }
                }
            }
        }
        result.addAll(allMap.values());

        Collections.sort(result, new AnalysisDataModelComparator());
        return result;
    }

    /**
     * 导出模板
     */
    private void exportExcel(List<ExportExcelModel> exportExcelModels, Template template, OutputStream os) {
        //选择模板并获得工作簿
        TemplateManage manage = new TemplateManage(template);
        Workbook wb = manage.getTemplate();

        List<Map<String, String>> list;
        String website;
        for (ExportExcelModel exportExcelModel : exportExcelModels) {
            list = exportExcelModel.getList();
            website = exportExcelModel.getWebsite();
            manage.writeDataToWorkbook(wb.getSheet(website), list);//为工作簿添加表格并加入数据
        }
        manage.export(wb, os);
    }
}
